package com.hx.login.web;

import com.hx.common.R;
import com.hx.common.api.MiaoshaUserService;
import com.hx.common.common.enums.ResultStatus;
import com.hx.common.common.resultbean.ResultGeekQ;
import com.hx.common.constant.GoodServerConstant;
import com.hx.common.constant.VerifyCodeConstant;
import com.hx.common.exception.GlobleException;
import com.hx.common.utils.VerifyCodeUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.ValidationEvent;

import java.awt.image.BufferedImage;
import java.io.OutputStream;
import java.util.Random;
import java.util.UUID;

import static com.hx.common.common.enums.ResultStatus.RESIGETER_FAIL;


@Controller
@RequestMapping("/user")
public class RegisterController {

    private static Logger logger = LoggerFactory.getLogger(RegisterController.class);

    @Autowired
    private MiaoshaUserService miaoShaUserService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @RequestMapping("/do_register")
    public String registerIndex(){
        return "register";
    }

    /**
     * 注册网站
     * @param userName
     * @param passWord
     * @param salt
     * @return
     */
    @RequestMapping("/register")
    @ResponseBody
    public R register(@RequestParam("username") String userName ,
                      @RequestParam("password") String passWord,
                      @RequestParam("verifyCode") String verifyCode,
                      @RequestParam("salt") String salt, HttpServletResponse response ){

        if (!verifyCode.equals(redisTemplate.opsForValue().get(VerifyCodeConstant.VCODE_REGISTER_PREFIX))){
            return R.error("验证码错误");
        }
        boolean registerInfo  = miaoShaUserService.register(response , userName,passWord,salt);
        if(!registerInfo){
           return R.error(RESIGETER_FAIL.getCode(),RESIGETER_FAIL.getMessage());
        }
        return R.ok();
    }

    @RequestMapping(value = "/verifyCodeRegister", method = RequestMethod.GET)
    @ResponseBody
    public R getMiaoshaVerifyCode(HttpServletResponse response) {
        try {
            String verifyCode = VerifyCodeUtil.generateVerifyCode(new Random());
            BufferedImage image = VerifyCodeUtil.createVerifyCode(verifyCode);
            OutputStream out = response.getOutputStream();
            ImageIO.write(image, "JPEG", out);
            out.flush();
            out.close();
            // 严谨的验证码应该对应每个请求使用不同的验证码，但考虑到高并发下一般还是直接采取第三方服务来提供验证码，因此这里只考虑不适用高并发的统一验证码实现
            redisTemplate.opsForValue().set(VerifyCodeConstant.VCODE_REGISTER_PREFIX, String.valueOf(VerifyCodeUtil.calc(verifyCode)));
            return R.ok();
        } catch (Exception e) {
            logger.error("生成验证码错误-----注册:{}", e);
            throw new GlobleException(ResultStatus.CODE_GEN_FAIL);
        }
    }
}
